package com.lizx.persional.common.filter;

import com.lizx.persional.common.config.CorsProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by lining on 17-9-19.
 */
public class CorsFilter implements Filter {

    @Autowired
    private CorsProperties corsProperties;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                filterConfig.getServletContext());
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        String allowedOrigin = corsProperties.getAllowedOrigin();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(allowedOrigin)) {
            String[] allowedOrigins = allowedOrigin.split(",");
            if (allowedOrigins != null && allowedOrigins.length > 0) {
                for (String origin : allowedOrigins) {
                    httpServletResponse.setHeader("Access-Control-Allow-Origin", origin);
                }
            }
        } else {
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        }

        httpServletResponse.setHeader("Access-Control-Allow-Headers", "User-Agent,Origin,Cache-Control,Content-type,Date,Server,withCredentials,AccessToken");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        httpServletResponse.setHeader("Access-Control-Max-Age", "1209600");
        httpServletResponse.setHeader("Access-Control-Expose-Headers", "token");
        httpServletResponse.setHeader("Access-Control-Request-Headers", "token");
        httpServletResponse.setHeader("Expires", "-1");
        httpServletResponse.setHeader("Cache-Control", "no-cache");
        httpServletResponse.setHeader("pragma", "no-cache");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

}
